'use strict';

var classBuilder = require('../../util/classBuilder'),
    Task = require('../Task').Task,
    https = require('https'),
    HttpsTask = classBuilder.define({
        base: Task,
        type: 'httpsTask',
        async: true, // Need to set it so next() will not be called outside the execute method

        construct: function (conf) {
            HttpsTask.base.constructor(conf); // Call the base constructor

            this.host = conf.host;
            this.path = conf.path;
            this.method = conf.method;
            this.port = conf.port || 443;
        },

        execute: function (params, error) {
            var me = this,
            conf = {
                host: me.host,
                path: me.path,
                method: me.method,
                port: me.port
            },
            request = https.request(conf, function (response) {
                var text = '';

                response.on('data', function (chunk) {
                    text += chunk.toString('utf8');
                });

                response.on('end', function () {
                    me.results = text;
                    me.next();
                });
            });

            request.on('error', function (error) {
                me.error = error;
                me.next();
            });

            request.end();
        }
    });

Task.registerType(HttpsTask.prototype.type, HttpsTask);